if (get_cookie("key")) {
    $.ajax({
        url: ip + "index.php?s=admincms/login/isadmin",
        type: "post",
        data: {
            "user": get_cookie("user"),
            "key": get_cookie("key")
        },
        success: function (_res) {
            res = JSON.parse(_res);
            if (res.resStatus === 0) {
                // 用户写入页面
                $("#user_name").text(res.data[0].NickName);
                $(".content_left>ul").empty();
                var url=location.href;
                var tiao=true;
                $.each(res.data[0].power_list,function (i,o) {
                    if(url.indexOf(o.url)!==-1){
                        tiao=false;
                    }
                    var _background_=  url.indexOf(o.url)!==-1?'style="background:#000;"':"";

                    $(".content_left>ul").append('<a href="'+o.url+'"> <li '+_background_+'><span class="glyphicon '+o.icon+'"></span><p>'+o.names+'</p></li></a>');

                });

                if(tiao){
                    location.href=res.data[0].power_list[0].url;
                }
            }
            if (res.resStatus === 1) {
                location.href = key_address;
            }
        },
        error: function () {
            location.href = key_address;
        }
    });
} else {
    location.href = key_address;
}
if (!localStorage.arr_danwei) {
    localStorage.arr_danwei = JSON.stringify([]);
}
if (!localStorage.arr_chicun) {
    localStorage.arr_chicun = JSON.stringify([]);
}
$(function () {
    // 初始添加开始时间
    $('#add_gongcheng_end_time').daterangepicker({
        timePicker: true,
        timePickerIncrement: 30,
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            applyLabel: '应用',
            cancelLabel: '取消',
            daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
        }
    });
    // 初始添加结束时间
    $('#add_gongcheng_start_time').daterangepicker({
        timePicker: true,
        timePickerIncrement: 30,
        singleDatePicker: true,
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            applyLabel: '应用',
            cancelLabel: '取消',
            daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
        }
    });
    // 初始修改开始时间
    $('#add_caigou_time').daterangepicker({
        timePicker: true,
        timePickerIncrement: 30,
        singleDatePicker: true,
        parentEl:"#yuangong_add",
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            applyLabel: '应用',
            cancelLabel: '取消',
            daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
        }
    });
    // 初始修改结束时间
    $('#set_caigou_time').daterangepicker({
        timePicker: true,
        timePickerIncrement: 30,
        singleDatePicker: true,
        parentEl:"#yuangong_set",
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            applyLabel: '应用',
            cancelLabel: '取消',
            daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
        }
    });
    // 时间搜索
    $('#input_time').daterangepicker({
        timePicker: true,
        timePickerIncrement: 30,
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            applyLabel: '应用',
            cancelLabel: '取消',
            daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
            monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"]
        }
    });
    var houtai = {
        //防止频繁操作
        old_click_time: 1000,
        click_yes: function () {
            var now_tiem = new Date().getTime();
            if (now_tiem - houtai.old_click_time > 1000) {
                houtai.old_click_time = now_tiem;
                return true;
            } else {
                return false;
            }
        },
        linshi_search: {
            search: null,
            start_time: null,
            end_time: null,
            status: null
        },
        linshi_id: null,
        linshi_arrid: [],
        queren_type: null,//0未采购  1已采购
        list_ajax_page:1,
        //提示功能
        hint:function (str) {
            $(".hint").remove();
            $("body").append("<div class='hint'>"+str+"</div>");
            $(".hint").slideDown(300).delay(2000).slideUp();
        },
        jiancha: function () {
            // 判断是够为空
            for (var i = 0; i < $(".add_goods_body .input_is:visible").length; i++) {
                if ($(".add_goods_body .input_is:visible").eq(i).val() === "") {
                    $(".add_goods_body .input_is:visible").eq(i).focus();
                    houtai.hint("请填写 " + $(".add_goods_body .input_is:visible").eq(i).prev().text());
                    return false;
                }
            }
            return true;
        },
        shop_list_ajax: function (page_number) {
            var n = page_number ? page_number : houtai.list_ajax_page=1;
            $.ajax({
                url: ip + "index.php?s=admincms/Goodsgather/showList",
                type: "post",
                data: {
                    token: get_cookie("key"),
                    page: n,
                    pid :houtai.linshi_search.search,
                   startTime:houtai.linshi_search.start_time,
                    endTime:houtai.linshi_search.end_time,
                    status:houtai.linshi_search.status
        },
                success: function (_res) {
                    var res = JSON.parse(_res);
                        console.log(res);
                        houtai.table_string(res);
                        $("#page").sdpagination({
                            boxClass: 'sdpagination',
                            totalCount:res.totalpage,           //总条数
                            pageSize:10,                //每页显示
                            pageIndex: n,                //当前页数
                            preText: '上页',                                  //上一页按钮显示的字符
                            nextText: '下页',                                 //下一页按钮显示的字符
                            firstText: '首页',                                //首页按钮显示的字符
                            lastText: '末页',                                 //末页按钮显示的字符
                            showNearby: 3,                                    //当前按钮前后按钮数
                            infoTemplet: '每页{pageSize} 共{totalCount} 当前{pageIndex}/{pageCount}',//自定义信息模板
                            pageList: [5, 10, 20],                            //设置PageSize下拉框的选择项，
                            onPageIndexChange: function (pageIndex) { //回调，点击按钮时或者输入页数时，激发onPageIndexChange事件，回调参数为 新页数、PageSize
                                houtai.list_ajax_page=pageIndex;
                                houtai.shop_list_ajax(pageIndex);
                            }
                        });

                }
            });
        },
        table_string: function (res) {
            // 写入table
            var string_head = "<thead><tr><th>ID</th><th>需求人</th><th>商品</th><th>数量</th><th>时间</th><th>状态</th><th>操作</th></tr></thead>";
            var string_body = "";
          if (res.resStatus===0) {

              $.each(res.data, function (i, o) {
                  var status_btn="";
                  var status_string="";
                  if(o.status===0){
                      status_btn='<button type="button" class="btn btn-success btn-xs yicaigou">已采购</button>';
                      status_string='<span class="confirm">未采购</span> ';
                  }else{
                      status_btn='<button type="button" class="btn btn-danger btn-xs weicaigou"> 未采购</button>';
                      status_string='<span class="complete">已采购</span> ';
                  }
                    string_body +='<tr>' +
                        '<td style="vertical-align: middle" class="caigou_id">' +o.id + '</td>' +
                        '<td style="vertical-align: middle" class="caigou_user">' + o.names + '</td>' +
                        '<td style="vertical-align: middle" class="caigou_name">' + o.goodsName + '</td>' +
                        '<td style="vertical-align: middle" class="caigou_number">' +o.amount + '</td>' +
                        '<td style="vertical-align: middle;max-width: 250px;" class="caigou_time">' +o.createTime + '</td>' +
                        '<td style="vertical-align: middle;max-width: 250px;" class="caigou_status">' +status_string + '</td>' +
                        '<td style="vertical-align: middle;width: 150px;" class="caigou_controls text-center"> <button type="button" class="btn btn-warning btn-xs set"> <span class="glyphicon glyphicon-tags" aria-hidden="true"></span> 修改</button> '+status_btn+'</td>' +
                        '</tr>';
                });
          }else{
                string_body = "<tr class='text-center'><td colspan='13'>没有数据</td></tr>";
            }

                $("table").empty().append(string_head + string_body);
        },
        tianjia: function () {
                $(".loading").fadeIn(200);
                var obj = {
                    names:$.trim($("#add_caigou_name").val()),
                    amount:$.trim($("#add_caigou_number").val()),
                    pid:$.trim($("#add_caigou_goodsName").val()),
                    token:get_cookie("key")
                };

                $.ajax({
                    url: ip + "index.php?s=admincms/Goodsgather/add",
                    data: obj,
                    type: "post",
                    success: function (_res) {
                    var res=JSON.parse(_res);
                        if (res.resStatus === 0) {
                            $(".loading").fadeOut();
                            $("#yuangong_add").fadeOut();
                            houtai.shop_list_ajax(1);
                            houtai.hint("<p class='text-success'>添加成功了！</p>");
                            $(".add_goods_body .input_is:visible").val("");
                        } else if (res.resStatus === 1) {
                            houtai.hint("添加失败了！");
                            $(".loading").fadeOut(200);
                        }
                    },
                    error: function () {
                        houtai.hint("<p>添加失败了！</p>");
                        $(".loading").fadeOut(200);
                    }
                });
        },
        xiugai: function () {
                $(".loading").fadeIn(200);
                var obj = {
                    id:houtai.linshi_id,
                    names:$.trim($("#set_caigou_name").val()),
                    amount:$.trim($("#set_caigou_number").val()),
                    pid:$.trim($("#set_caigou_goodsName").val()),
                    token:get_cookie("key")
                };
                $.ajax({
                    url: ip + "index.php?s=admincms/Goodsgather/edit",
                    data: obj,
                    type: "post",
                    success: function (res) {
                        if (JSON.parse(res).resStatus === 0) {
                            $(".loading").fadeOut();
                            $("#yuangong_set").fadeOut();
                          houtai.shop_list_ajax(houtai.list_ajax_page);
                            houtai.hint("<p class='text-success'>修改成功了！</p>");
                        } else{
                            houtai.hint("修改失败了！");
                            $(".loading").fadeOut(200);
                        }
                    },
                    error: function () {
                        $(".loading").fadeOut(200);
                        houtai.hint("<p>修改失败了！</p>");
                    }
                });

        },
        set_caigou_status: function (status) {
            var obj = {
                status:status,
                id: houtai.linshi_id,
               token: get_cookie("key")
            };
            $.ajax({
                url: ip + "index.php?s=admincms/Goodsgather/isComplete",
                data: obj,
                type: "post",
                success: function (res) {
                    console.log(res);
                    if (JSON.parse(res).resStatus === 0) {
                        $("#modal_wrap").fadeOut(200);
                        houtai.shop_list_ajax(houtai.list_ajax_page);
                        houtai.hint("<p class='text-success'>修改成功了！</p>");

                    }else{
                        houtai.hint("操作失败！！");
                    }
                },
                error:function () {
                    houtai.hint("操作失败！！");
                }
            });
        }
    };

    // 请求数据
    houtai.shop_list_ajax();
    // 收展事件
    $(".right-top>b").bind("click", function () {
        if ($(".content_left").is(":hidden")) {
            $(".content_left").removeClass("ishidden");
            $(".content_right").removeClass("iskuozhang");
        } else {
            $(".content_left").addClass("ishidden");
            $(".content_right").addClass("iskuozhang");
        }
    });

    // 莫态框取消modal
    $("#modal_close").bind("click", function () {
        $("#modal_wrap").fadeOut(200);

    });
    // 修改取消
    $(".cancle_set").bind("click", function () {
        $(".set_shangpin").fadeOut(200);
    });
    // 修改
    $("table").on("click", ".set", function () {
        houtai.linshi_id = $(this).parents("tr").find(".caigou_id").text();
        $("#set_caigou_name").val($(this).parents("tr").find(".caigou_user").text());
        $("#set_caigou_goodsName").val($(this).parents("tr").find(".caigou_name").text());
        $("#set_caigou_number").val($(this).parents("tr").find(".caigou_number").text());
        $("#yuangong_set").fadeIn();
    });
    // 已采购
    $("table").on("click", ".yicaigou", function () {
        houtai.linshi_id = $(this).parents("tr").find(".caigou_id").text();
        houtai.queren_type=1;
        $(".modal-body").empty().append("确定把<span style='color:#f10'>"+$(this).parents('tr').find('.caigou_name').text()+"</span>修改为<span style='color: #68ca65'>已采购</span>吗？");
        $("#modal_wrap").show();

    });
    // 未采购
    $("table").on("click", ".weicaigou", function () {
        houtai.queren_type=0;
        houtai.linshi_id = $(this).parents("tr").find(".caigou_id").text();
        $(".modal-body").empty().append("确定把<span style='color:#f10'>"+$(this).parents('tr').find('.caigou_name').text()+"</span>修改为<span style='color: #fc1a18'>未采购</span>吗？");
        $("#modal_wrap").show();
    });

    // 确认删除
    $("#confirm").bind("click", function () {
        if(houtai.queren_type===0){
            houtai.set_caigou_status(0);
        }else if(houtai.queren_type===1){
            houtai.set_caigou_status(1);
        }

    });
    $("#add").bind("click", function () {
        if(houtai.jiancha()){
                if (houtai.click_yes()) {
                    houtai.tianjia();
                }

        }

    });
    $("#set").bind("click", function () {
        if(houtai.jiancha()) {
            var start_time=new Date($("#set_gongcheng_start_time").val()).getTime();
            var end_time=new Date($("#set_gongcheng_end_time").val()).getTime();
            if(end_time<=start_time){
                $("#set_gongcheng_end_time").focus();
                houtai.hint("工期结束时间 不能小于或等于 开始时间");
            }else{
                if (houtai.click_yes()) {
                    houtai.xiugai();
                }
            }
        }
    });
    // 按状态查找采购商品
    $("#select1").bind("change",function () {
         houtai.linshi_search.status=$(this).val()===""?null:$(this).val();
         houtai.linshi_search.start_time="";
         houtai.linshi_search.end_time="";
         houtai.linshi_search.search="";
         houtai.shop_list_ajax();
    });
    // 按时间查找
    $("#search_time").bind("click",function () {
        if ($("#input_time").val() === "") {
            $("#input_time").focus();
            houtai.hint("请输入搜索内容");
        } else {
            if (houtai.click_yes()) {
                // 匹配的正则表达式
                var regexp = /(\d+-\d+-[^-]+)-(.+)/;
                houtai.linshi_search.start_time = new Date($("#input_time").val().match(regexp)[1]).getTime() / 1000;
                houtai.linshi_search.end_time = new Date($("#input_time").val().match(regexp)[2]).getTime() / 1000;
               houtai.linshi_search.search="";
                houtai.shop_list_ajax();
            }
        }
    });
    // 添加员工按钮
    $("#yuangong_add_btn").bind("click", function () {
        $("#add_gongcheng_start_time").val("");
        $("#add_gongcheng_end_time").val("");
        $("#yuangong_add").fadeIn();
    });
    // 搜索员工按钮
    $("#search_all").bind("click", function () {
        if ($.trim($("#search_input").val()) === "") {
            houtai.hint("请输入内容再搜索！！");
            $("#search_input").focus();
        }else{
            houtai.linshi_search.search=$.trim($("#search_input").val());
            houtai.linshi_search.start_time ="";
            houtai.linshi_search.end_time ="";
            houtai.linshi_search.status ="";
            houtai.shop_list_ajax();
        }
    });
     //回车搜索员工
    $("#form_search").submit(function () {
        if ($.trim($("#search_input").val()) === "") {
            houtai.hint("请输入内容再搜索！！");
            $("#search_input").focus();
        }else{
            houtai.linshi_search.search=$.trim($("#search_input").val());
            houtai.shop_list_ajax();
        }
        return false;
    });
    //退出按钮
    $("#exit").bind("click", function () {
        set_cookie("key", "", 0);
        location.href = key_address;
    });
    //头像按钮
    $(".right-top>div").bind("click", function (e) {
        $("#exit").slideToggle();
        e.stopPropagation();
    });
    $(window).bind("click", function () {
        $("#exit").slideUp();
    });
});
